package com.example.ch14fragmentsbooks

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.book_description.*
import kotlinx.android.synthetic.main.book_titles.*

class BookTitle : Fragment() , View.OnClickListener{

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val v = inflater.inflate(R.layout.book_titles,container,false)
        return v
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        rlas3.setOnClickListener(this)
        rlas3kotlin.setOnClickListener(this)
        rminandroid.setOnClickListener(this)
    }


    override fun onClick(v: View?) {
        var index:Int =0
        when(v?.id){
            R.id.rlas3 ->{
                index=0
            }
            R.id.rlas3kotlin ->{
                index=1
            }
            R.id.rminandroid ->{
                index =2
            }
        }
         val ac = activity
        if(ac is Coordinator){
            ac.onBookChanged(index)
        }

    }

}

class BookDescription:Fragment(){
    lateinit var arrbookdesc:Array<String>
    var bookindex =0
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        var v = inflater.inflate(R.layout.book_description,container,false)
        arrbookdesc = resources.getStringArray(R.array.bookdescriptions)
        bookindex = if(savedInstanceState?.getInt("bookindex")==null) 0
            else (savedInstanceState?.getInt("bookindex"))
        return v
    }

    override fun onSaveInstanceState(outState: Bundle) {
        outState.putInt("bookindex",bookindex)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        changeDescription(bookindex)
    }

    fun changeDescription(index:Int):Unit{
        bookindex=index
        println("BOOK INDEX = $bookindex")
        txt_description?.setText(arrbookdesc[bookindex]);
        println(arrbookdesc[bookindex])
    }
}